package com.yeebo.utils;

import com.aliyun.oss.OSSClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * 阿里云OSS云存储工具类
 */
@Component
public class AliYunOSSUtils {
    private static Logger logger = LoggerFactory.getLogger(AliYunOSSUtils.class);

    private static final String END_POINT = "http://oss-cn-zhangjiakou.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAIHe4gMBhkFQdB";
    private static final String ACCESS_KEY_SECRET = "5HhUiCUwxeZcRgGvyyZHqsmq3kQ9Fw";
    private static final String BUCKET_NAME = "haha-wallet";
    private static final String ACCESS_BUCKET_DOMAIN = "https://haha-wallet.oss-cn-zhangjiakou.aliyuncs.com/";

    private static OSSClient ossClient;

    private OSSClient getOssClient() {
        if (ossClient == null) {
            ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        }
        return ossClient;
    }

    public String putFileAndGetUrl(MultipartFile file, String targetFilePath) {
        String url = null;
        try {
            InputStream inputStream = file.getInputStream();
            getOssClient().putObject(BUCKET_NAME, targetFilePath, inputStream);
            getOssClient().shutdown();
            url = ACCESS_BUCKET_DOMAIN + targetFilePath;
        } catch (Exception ex) {
            logger.error("上传文件报错，错误信息ex={}", ex);
        }
        logger.info("开始存储文件至指定目录{}，并返回访问URL={}", targetFilePath, url);
        return url;
    }

    public String putInputStreamAndGetUrl(InputStream inputStream, String targetFilePath) {
        String url = null;
        try {
            getOssClient().putObject(BUCKET_NAME, targetFilePath, inputStream);
            getOssClient().shutdown();
            url = ACCESS_BUCKET_DOMAIN + targetFilePath;
        } catch (Exception ex) {
            logger.error("上传文件报错，错误信息ex={}", ex);
        }
        logger.info("开始存储文件至指定目录{}，并返回访问URL={}", targetFilePath, url);
        return url;
    }

}
